package com.biz.primus.ms.promotion.dao.redis;

import com.biz.primus.ms.promotion.dao.ro.PresellProductRo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Repository;

/**
 * 预售商品RedisDao
 *
 * @author david-liu
 */
@Repository
public class PresellProductRedisDao extends BasePromotionProductRedisDao<PresellProductRo, String> {

    public Map<Long, List<PresellProductRo>> getPresellProductRos(Map<Long, List<Long>> promotionProductIds) {
        if (MapUtils.isNotEmpty(promotionProductIds)) {
            return Collections.emptyMap();
        }
        List<Integer> productSizeList = Lists.newArrayList();
        List<String> hashKeys = Lists.newArrayList();
        for (Map.Entry<Long, List<Long>> entry : promotionProductIds.entrySet()) {
            productSizeList.add(entry.getValue().size());
            for (Long productId : entry.getValue()) {
                hashKeys.add(super.getHashKey(String.format("%s_%s", entry.getKey(), productId)));
            }
        }
        List<PresellProductRo> presellProductRos = super.findByKeys(hashKeys);
        Integer startIndex = 0;
        Set<Long> promotionIds = promotionProductIds.keySet();
        Iterator<Long> iterator = promotionIds.iterator();
        Map<Long, List<PresellProductRo>> ret = Maps.newLinkedHashMap();
        for (Integer size : productSizeList) {
            ret.put(iterator.next(), presellProductRos.subList(startIndex, startIndex + size));
            startIndex = startIndex + size;
        }
        return ret;
    }

    public Boolean changePresellProductStock(Long promotionId, Long productId, Integer quantity) {
        return super.changePromotionProductStock(promotionId, productId, quantity);
    }

    public PresellProductRo getPresellProductRo(Long promotionId, Long productId) {
        return super.findOne(String.format("%s_%s", promotionId, productId));
    }
}
